/*
window.log = function(){
	log.history = log.history || [];
	log.history.push(arguments);
	arguments.callee = arguments.callee.caller;
	if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});
*/

(function(){
	window.eight1 = {
		has:{
			init:function(){
				eight1.has.autofocus == 'autofocus' in document.createElement('input');
				eight1.has.svg = !!(document.createElementNS && document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect);
			}
		},
		init:function(){
			/// <summary>Initializes custom functionality before all page elements are ready.</summary>
			
			// init feature detection
			eight1.has.init();
			
			// set focus on search
			// NOTE: The user cannot actually submit the search at this time, but the search box will at least exist
			if(!eight1.has.autofocus){ document.getElementById('search').focus(); }

			// TODO: eight1.ready(eight1.load);
		},
/*
		load:function(){
			/// <summary>Loads custom functionality after all page elements are ready.</summary>
		},
		ready:function(f,d){
			/// <param name="f">The function to call when the event is triggered.</param>
			/// <param name="d">Placeholder for the <see cref="document"/> element.</param>
			
			d = document;
			if(d.addEventListener){
				d.addEventListener('DOMContentLoaded', function(){
					d.removeEventListener('DOMContentLoaded', arguments.callee, false);
					f();
				}, false);
			}else if(d.attachEvent){
				d.attachEvent('onreadystatechange', function(){
					if(d.readyState == 'complete'){
						d.detachEvent('onreadystatechange', arguments.callee);
						f();
					}
				});
				if(d.documentElement.doScroll && window == window.top){
					(function(){
						if(f){ return; }
						try{ d.documentElement.doScroll('left'); }catch(error){ setTimeout(arguments.callee, 0); return; }
						f();
					})();
				}
			}
		},
		add:function(el,e,f){
			/// <param name="el">The element to set add the event handler for.</param>
			/// <param name="e">The event to add the handler for.</param>
			/// <param name="f">The function to call when the event is triggered.</param>
			
			if(el.addEventListener){
				el.addEventListener(e, f, false);
				el.addEventListener(e, f, false);
			}else if(el.attachEvent){
				el.attachEvent('on'+e, f);
				el.attachEvent('on'+e, f);
			}else{
				el['on'+e] = f;
				el['on'+e] = f;
			}
		},
*/
		set:function(o,q,n,f,s,sp,i,a,t,st){
			/// <summary>Applies page configuration settings.</summary>
			/// <param name="o">Options to set.</param>
			/// <param name="q">Placeholder for the querystring tile overrides.</param>
			/// <param name="n">Placeholder for the nav element.</param>
			/// <param name="f">Placeholder for the form element.</param>
			/// <param name="s">Placeholder for the search box (input) element.</param>
			/// <param name="sp">Placeholder to specify whether the search provider has been set.</param>
			/// <param name="i">Placeholder for the loop iterator.</param>
			/// <param name="a">Placeholder for the collection of a elements within the <paramref name="n"/>.</param>
			/// <param name="t">Placeholder for tile config info associated with the <paramref name="a"/> within the loop.</param>
			/// <param name="st">Placeholder for dynamic styles that need to be added to the page.</param>
			
			// override options with querystring
			var q = location.search.substring(1).split(',');
			for(i=0; i<q.length; i++){ if(q[i].length>0) o.tiles[i] = q[i]; }
			
			// get search fields
			n = document.body.getElementsByTagName('nav')[0];
			f = n.getElementsByTagName('form')[0];
			s = document.getElementById('search');
			
			// set links
			a = n.getElementsByTagName('a');
			for(i=0,sz=0,svg=0; i<a.length; i++){
				// get next tile number
				t = a[i].id.replace('tile','')-1;
				
				// get from options or skip
				if(!(t in o.tiles)){ continue; }
				t = o.tiles[t];
				
				// check common tiles
				t = eight1.tiles[t] || t;
				
				// if tile is a string, the lookup key was not found 
				if(typeof(t) == 'string'){
					a[i].title = 'The tile key, "' + t + '", was not found. Please include a name and URL.';
					a[i].innerHTML = t + '?';
					continue;
				}
				
				// save friendly name for file naming conventions
				t.friendly = t.name.toLowerCase().replace(/[^a-zA-Z0-9]/g, '');
				
				// set link url
				a[i].href = t.url;

				// set background color
				if(t.bg){
					a[i].style.backgroundColor = t.bg;
					(st || (st = document.createStyleSheet())).addRule('a#tile'+(i+1)+':hover', 'border-color:'+t.bg+';box-shadow:0 0 15px '+t.bg);
				}
				
				// if tile supports search and search not set, use tile's search
				if(t.search && !sp){
					f.action = t.search;
					s.setAttribute('placeholder', 'Search '+t.name);
					sp = true;
				}
				
				// if no image, use text and continue
				if(!t.img){ a[i].innerText = t.name; continue; }

				// add svg/png
				sz=(function(hw,pc,wd,pr){
					/// <param name="hw">Size of the SVG image.</param>
					/// <param name="pc">Placeholder for the padded percent of the body to use for the SVG image.</param>
					/// <param name="wd">Placeholder to specify whether the size is wider than it is tall.</param>
					/// <param name="pr">Placeholder for the product of the height * width.</param>
					
					if(!hw){ return; }
					pc = .75;
					hw = { w:hw.w/hw.h, h:hw.h/hw.w };
					
					// if svg is wider than tile, size by width; otherwise, size by height
					if(hw.h/hw.w < eight1.tiles.sizes[i].h/eight1.tiles.sizes[i].w){
						hw.w = eight1.tiles.sizes[i].w * pc;
						hw.h = hw.w * hw.h;
					}else{
						hw.h = eight1.tiles.sizes[i].h * pc;
						hw.w = hw.w * hw.h;
					}
					return hw;
				})(t.img.svg);
				svg = (t.img.svg && eight1.has.svg);
				a[i].innerHTML = ['<img',
					' src="tiles/', t.friendly, '.', svg?'svg':'png', '"',
					' alt="',t.name,'"', 
					' onerror="document.getElementById(\'',a[i].id,'\').innerHTML=\'', t.name, '\'"', 
					svg ? ' type="image/svg+xml"' : '',
					svg ? ' height="'+sz.h+'"'    : '',
					svg ? ' width="'+sz.w+'"'     : '',
					'/>'].join('');
			}
			
			// if search not set, use default
			if(!sp){
				f.action = eight1.tiles.bing.search;
				s.setAttribute('placeholder', 'Search Bing');
			}
		},
		tiles : {
			sizes:[
				{ w:440, h:215 },
				{ w:420, h:205 },
				{ w:330, h:160 },
				{ w:290, h:140 },
				{ w:215, h:103 },
				{ w:215, h:102 },
				{ w:195, h:98 },
				{ w:195, h:97 },
				{ w:160, h:75 },
				{ w:160, h:75 },
				{ w:140, h:65 },
				{ w:140, h:65 }
			],
			amazon        :{ name:'Amazon',          url:'http://amazon.com',                     img:{ svg:{w:940,    h:195  }        } },
			bbcnews       :{ name:'BBC News',        url:'http://bbc.co.uk/news',                 img:{ svg:{w:212,    h:33   }, png:1 } },
			bing          :{ name:'Bing',            url:'http://bing.com',                       img:{ svg:{w:148,    h:56   }, png:1 }, search:'http://www.bing.com/search' },
			cnn           :{ name:'CNN',             url:'http://cnn.com',          bg:'#ca0002', img:{ svg:{w:200,    h:95+75}, png:1 } },  // added height to shrink
			deviantart    :{ name:'DeviantART',      url:'http://deviantart.com',                 img:{                          png:1 } },
			facebook      :{ name:'Facebook',        url:'http://facebook.com',     bg:'#3b5998', img:{ svg:{w:210,    h:44   }, png:1 } },
			flickr        :{ name:'Flickr',          url:'http://flickr.com',       bg:'#0063db', img:{ svg:{w:514+85, h:156  }        } },  // added width to shrink
			google        :{ name:'Google',          url:'http://google.com',                     img:{ svg:{w:800,    h:283  }, png:1 }, search:'http://www.google.com/search' },
			grooveshark   :{ name:'Grooveshark',     url:'http://grooveshark.com',                img:{                          png:1 } },
			hulu          :{ name:'Hulu',            url:'http://hulu.com',         bg:'#6ab040', img:{ svg:{w:300+60, h:100  }        } },  // added width to shrink
			itunes        :{ name:'iTunes',          url:'http://apple.com/itunes',               img:{                          png:1 } },
			lastfm        :{ name:'Last.fm',         url:'http://last.fm',          bg:'#ce0000', img:{                          png:1 } },
			netflix       :{ name:'Netflix',         url:'http://netflix.com',      bg:'#b9090b', img:{ svg:{w:311,    h:98   }        } },
			twitter       :{ name:'Twitter',         url:'http://twitter.com',      bg:'#35cdff', img:{ svg:{w:480,    h:110  }, png:1 } },
			weatherchannel:{ name:'Weather Channel', url:'http://weather.com',      bg:'#244aa5', img:{ svg:{w:138+60, h:67   }        } },  // added width to shrink
			wikipedia     :{ name:'Wikipedia',       url:'http://wikipedia.org',                  img:{                          png:1 } },
			yahoo         :{ name:'Yahoo',           url:'http://yahoo.com',        bg:'#7b0099', img:{ svg:{w:800,    h:151  }, png:1 }, search:'http://search.yahoo.com/bin/search' },
			youtube       :{ name:'YouTube',         url:'http://youtube.com',      bg:'#ca1818', img:{ svg:{w:545+85, h:220  }, png:1 } }   // added width to shrink
		}
	};
	eight1.init();
})();